<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

{% extends "application.html" %}

{% block content %}

<!-- Plans -->
<div class="plans">
  <button type="button" class="reset close"><span aria-hidden="true">Reset View</span></button>
  <div class="row">
    <div class="col-md-6 text-center">
      <h4 class="space-above">Logical Topology</h4>
    </div>
    <div class="col-md-6 text-center">
      <h4 class="space-above">
        <span id="container-count"></span> Containers and
        <span id="instance-count"></span> Instances</h4>
    </div>
  </div>
  <div class="row graphics text-center">
    <div class="col-md-6 vcenter">
      <div id="logical-plan"></div>
    </div><!-- Can't have spaces in here - see http://stackoverflow.com/questions/20547819/vertical-align-with-bootstrap-3
    --><div class="col-md-6 vcenter">
      <div id="physical-plan"></div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-6 text-center col-md-offset-6">
      <div id="color-key" class="text-center"></div>
    </div>
  </div>
</div>

<!-- Topology Info -->
<div class="col-md-12">
  <table class="table">
    <thead>
      <th>Topology name</th>
      <th>Status</th>
      <th>Cluster</th>
      <th>Role</th>
      <th>Environment</th>
      <th>Version</th>
      <th>Launched at</th>
      <th>Submitted by</th>
      <th>Links</th>
    </thead>

    <tbody>
      <tr>
        <td>{{topology}}</td>
        <td>{{execution_state['status']}}</td>
        <td>{{cluster}}</td>
        <td>{{execution_state['role']}}</td>
        <td>{{environ}}</td>
        <td>{{execution_state['release_version']}}</td>
        <td>{{launched}}</td>
        <td>{{execution_state['submission_user']}}</td>
        <td>
          <a id="jobPageLink" class="btn btn-primary btn-xs" href={{job_page_link}} target="_blank">Job</a>
          {% for extra_link in execution_state['extra_links'] %}
            <a id="{{extra_link['name']}}" class="btn btn-primary btn-xs" href="{{extra_link['url']}}" target="_blank">{{extra_link['name']}}</a>
          {% end %}
        </td>
      </tr>
    </tbody>
  </table>
</div>

<!-- Details section. It contains a navigator and the details. -->
<div class="col-md-12">
  <!-- Navegator -->
  <div id="display-navigator">
    <div class="navbar-default">
      <div class="row navbar-collapse collapse navbar-responsive-collapse">
        <div class="btn-group navigator">
            <button type="button" id="stats" class="active">Stats</button>
            <button type="button" id="counters" class="">Counters</button>
            <button type="button" id="config" class="">Config</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Topology details, including stats, counter, and config. -->
  <div class="display-stats" id="topologydetails">
    <!-- Stats -->
    <div class="col-md-12">
      <div class="display-info space-above display-stats" id="topologystats">
        <div class="col-md-6">
          <div class="container">
            <div class="text-center">
              <span class="h5">Aggregate topology metrics</span>
              <span
                class="glyphicon glyphicon-question-sign bs-popover text-muted"
                aria-hidden="true"
                data-toggle="popover"
                data-placement="top"
                title="Aggregate Topology Metrics"
                data-html="true"
                data-content="
                  <p>Colors in this table show the worst value for any instance in the topology for each metric/time range.</p>
                  <p><strong class='status-circle' style='color: #1a9850'>&#11044;</strong> green metrics are healthy</p>
                  <p><strong class='status-circle' style='color: #fdae61'>&#11044;</strong> orange metrics are elevated</p>
                  <p><strong class='status-circle' style='color: #d73027'>&#11044;</strong> red indicates there may be a problem.</p>
                  Click on a circle to color instances by their value for that metric."></span>
            </div>
            <p class="text-muted text-center">
              <em>Click the circles below to color instances by metric over a time period</em>
            </p>
            <table class="stat-rollup-table">
              <tbody class="stats">
              </tbody>
              <tbody>
                <td class="text-right">
                  Role
                  <span
                    class="glyphicon glyphicon-question-sign bs-popover text-muted"
                    aria-hidden="true"
                    data-toggle="popover"
                    data-placement="top"
                    title="Role"
                    data-content="Color instances by their role from the logical plan.  This is the default behavior on page load."></span>
                </td>
                <td colspan="4">
                  <a href="#" id="reset-colors" class="strong">Color instances by role</a>
                </td>
              </tbody>
            </table>
            <div class="text-center">
              <div class="btn-group color-choice">
                <button type="button" class="btn btn-xs btn-default active" data-color="default">Default Colors</button>
                <button type="button" class="btn btn-xs btn-default" data-color="leonid">Colorblind Friendly</button>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-6">
          <div class="text-center">
            <span class="h5" id="trendline-title"></span>
            <span
              class="glyphicon glyphicon-question-sign bs-popover text-muted"
              aria-hidden="true"
              data-toggle="popover"
              data-placement="top"
              title="Metric Trendlines"
              data-html="true"
              data-content="
                <p>Trendline of topology metrics over the past hour.  Shows the entire topology by default.</p>
                <p>Click on a logical component of the topology to stats for just instances of that component.</p>
                <p>Click on an instance to get metrics, logs, and exceptions for that instance.</p>
                <p><em>When the entire topology or a single logical component is selected, values
                  show are the <strong>maximum</strong> across all instances.</em></p>
                "></span>
          </div>
          <div id="stat-trendlines" class="container">
          </div>
        </div>
      </div>
    </div>
    <!-- Counters -->
    <div class="col-md-12">
      <div class="col-md-12">
        <div id="display-counters"></div>
      </div>
      <!-- Popup dialog for parallelism calculator -->
      <div class="modal fade" id="parallelism-calculator-modal" tabindex="-1" role="dialog" aria-labelledby="parallelismCalculatorModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Parallelism Calculator: <span id="modal-component"></span></h5>
            </div>
            <div class="modal-body">
              <form class="form-horizontal">
                <h3 id="modal-component"></h3>
                <div class="form-group">
                  <label class="col-sm-8 control-label" for="target-execute-count">
                    Target execute count (current: <b id="modal-execute-count"></b>)</label>
                  <div class="col-sm-4">
                    <input id="target-execute-count" class="form-control form-control-sm" value="100"></input>
                  </div>
                </div>
                <div class="form-group">
                  <label class="col-sm-8 control-label" for="target-max-utilization">
                    Target max capacity utilization (current: <b id="modal-max-utilization"></b>)</label>
                  <div class="col-sm-3">
                    <input id="target-max-utilization" class="form-control form-control-sm" value=50 max=100 min=1></input>
                  </div>
                  <span class="col-sm-1 control-label">%</span>
                </div>
                <div class="form-group">
                  <label class="col-sm-8 control-label" for="target-parallelism">
                    Target parallelism (current: <b id="modal-parallelism"></b>)</label>
                  <div class="col-sm-4">
                    <input id="target-parallelism" class="form-control form-control-sm" readonly=true value="3"></input>
                  </div>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" onclick="calculateParallelism()">Calculate</button>
              <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Config -->
    <div class="col-md-12">
      <div class="col-md-12">
        <div id="display-config"></div>
      </div>
    </div>
  </div>
</div>

<script src="{{ static_url('js/d3.min.3.4.11.js') }}"></script>
<script src="{{ static_url('js/d3-tip.min.0.6.3.js') }}"></script>
<script src="{{ static_url('js/stat-trendlines.js') }}"></script>
<script src="{{ static_url('js/plan-controller.js') }}"></script>
<script src="{{ static_url('js/physical-plan.js') }}"></script>
<script src="{{ static_url('js/logical-plan.js') }}"></script>
<script src="{{ static_url('js/plan-stats.js') }}"></script>
<script src="{{ static_url('js/colors.js') }}"></script>
<script src="{{ static_url('js/topology-details.js') }}"></script>
<script type="text/jsx" src="{{ static_url('js/topologies.js') }}" ></script>
<script type="text/jsx" src="{{ static_url('js/config.js') }}"></script>

<script type="application/javascript">
  function calculateParallelism() {
    var calculator = $("#parallelism-calculator-modal");

    var execute_count = calculator.attr("data-execute-count");
    var max_utilization = calculator.attr("data-max-utilization");
    var parallelism = calculator.attr("data-parallelism");
    var target_execute_count = calculator.find('#target-execute-count').val();
    var target_max_utilization = calculator.find('#target-max-utilization').val();

    // Estimate the target parallelism based on the current information.
    var newParallelism = max_utilization * target_execute_count * parallelism /
                         (execute_count * target_max_utilization);
    calculator.find('#target-parallelism').val(Math.ceil(newParallelism));
  }
</script>

<script type="application/javascript">

  // colors used shading nodes in logical and physical plan
  var colors = [
    "#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd",
    "#8c564b","#e377c2","#17becf","#bcbd22","#aec7e8",
    "#ffbb78","#98df8a","#ff9896","#c5b0d5","#c49c94",
    "#f7b6d2","#9edae5","#dbdb8d"
  ].map(function (d) {
    // desaturate by 20% and lighten by 50%
    var hsl = d3.hsl(d);
    hsl.s *= 0.8;
    hsl.l = (1 + hsl.l) / 2;
    return hsl.toString();
  });

  var linestyle = {color:'#888', width:'3px', boldwidth: '6px'};

  window.onload = function() {

    // hide Job link if it is not there
    if ("{{job_page_link}}" === "") {
      document.getElementById("jobPageLink").style.display = "none";
    }

    // display the topology name as the title
    d3.select("#page-title")
      .append("p")
      .html('{{topology}}');

    var logicalPlan, physicalPlan, packingPlan;

    d3.json("./{{topology}}/logicalplan.json",
      function(data) {
        // if there are any errors display using dialog box
        if (data.status != "success") {
          console.log("Loading logical plan json failed!");
          return;
        }

        logicalPlan = data.result;
        if (physicalPlan && logicalPlan && packingPlan) {
          startRendering();
        }
      }
    );

    d3.json("./{{topology}}/physicalplan.json",
      function(data) {
        // if there are any errors display using dialog box
        if (data.status != "success" ) {
          console.log("Loading physical plan json failed!");
          return;
        }

        physicalPlan = data;
        if (physicalPlan && logicalPlan && packingPlan) {
          startRendering();
        }
      }
    );

    d3.json("./{{topology}}/packingplan.json",
      function(data) {
        // if there are any errors display using dialog box
        if (data.status != "success" ) {
          console.log("Loading packing plan json failed!");
          return;
        }

        packingPlan = data.result;
        if (physicalPlan && logicalPlan && packingPlan) {
          startRendering();
        }
      }
    );

    function resizeDetailsSection() {
      const minSectionHeight = 350;  // Minimal height in pixel.
      var windowH = $(window).height();
      var planH = $(".plans").height();
      var detailsH = Math.max(minSectionHeight, windowH - planH - 222);  // Leave 222 pixels for topology info.

      d3.selectAll("div#topologydetails").style('height', detailsH + 'px');
    }

    function render(planController) {
      drawLogicalPlan(planController, logicalPlan, "#logical-plan", $("#logical-plan").width(), 400, "{{baseUrl}}",
          "{{cluster}}", "{{environ}}", "{{topology}}");
      drawPhysicalPlan(planController, physicalPlan, packingPlan, "#physical-plan", $("#physical-plan").width(), 400, "{{baseUrl}}", "{{cluster}}",
          "{{environ}}", "{{topology}}");

      resizeDetailsSection();

      planController.planResized();
    }

    function startRendering() {
      var planController = new PlanController("{{baseUrl}}", "{{cluster}}", "{{environ}}", "{{topology}}", physicalPlan, logicalPlan);
      $(window).on('resize', _.debounce(function () {
        render(planController);
      }, 100));
      render(planController);
      drawStatsTable(planController, "{{baseUrl}}", "{{cluster}}", "{{environ}}", "{{topology}}", physicalPlan, logicalPlan);

      planController.planDrawn();
    }
  };
</script>

<script type="text/jsx">
  /** @jsx React.DOM */
  React.renderComponent(
    <AllMetrics baseUrl="{{baseUrl}}" cluster="{{cluster}}" environ="{{environ}}" topology="{{topology}}"/>,
    document.getElementById('display-counters')
  );

  React.renderComponent(
    <ConfigTable baseUrl="{{baseUrl}}" cluster="{{cluster}}" environ="{{environ}}" topology="{{topology}}" />,
    document.getElementById("display-config")
  );
</script>

{% end %}
